# -*- coding: utf-8 -*-

from xsl import XLSWriter
from common import excel_folder_path, config_data

from vic.exchange.vic_huobi.huobi_http import HuobiHttp
from vic.exchange.vic_okex.okexft_http import OkexftHttp

conf = config_data()
url       = conf.get('OKEX_URL')
apiKey    = conf.get('OKEX_APIKEY')
apiSecret = conf.get('OKEX_APISECRET')

def okex_exchange_rate(ofh):
    return ofh.exchange_rate()

def okex_position(ofh):
    contract_type = 'this_week'
    symbol = 'btc_usd'
    p = ofh.future_position(symbol, contract_type)
    print p
    return p

def okex_future_userinfo(ofh):
    """获取OKEx合约账户信息(全仓)"""
    info = ofh.future_userinfo()['info']

    file_path = u'%s/' % excel_folder_path()
    sheet_name = u'okex逐仓账户列表.xls'
    file = file_path + sheet_name
    xlswriter  = XLSWriter(file=file.encode('utf8'))
    export_title = [u'币种' ,u'账户权益', u'保证金', u'已实现盈亏', u'未实现盈亏', u'保证金率']
    xlswriter.writerow(export_title, sheet_name=sheet_name)

    for account_type, account_info  in info.iteritems():
        account_rights = account_info.get('account_rights')
        keep_deposit   = account_info.get('keep_deposit')
        profit_real    = account_info.get('profit_real')
        profit_unreal  = account_info.get('profit_unreal')
        risk_rate      = account_info.get('risk_rate')

        data = [account_type ,account_rights, keep_deposit, profit_real, profit_unreal, risk_rate]
        xlswriter.writerow(data, sheet_name=sheet_name)

    xlswriter.save()

    return True

def huobi_ganggan():
    """获取货币杠杆账户信息"""

    huobi_http = HuobiHttp(url, apiKey, apiSecret)
    accounts=huobi_http.accounts()
    huobi_list, data_list = [], []
    print('account:%s'% accounts)
    for a in accounts['data']:
        data=huobi_http.balance(a['id'])['data']
        for info in data['list']:
            currency = info['currency']
            balance  = info['balance']
            if float(balance) > 0:
                print(info)

def depth_get_best(symbol, contract_type, size=200, merge=0):
    """获取深度交易最好的价格和数量"""

    ft_http = OkexftHttp(url, apiKey, apiSecret)
    depth = ft_http.future_depth(symbol, contract_type, size, merge)

    bids  = depth['bids']

    # 成交价列表中的成交量除以成交价
    divided_list   = [float(d[0])/float(d[1]) for d in bids]

    # 获取成交价格最合适的成交索引
    min_deal_index = divided_list.index(min(divided_list))
    print(bids)
    print(min_deal_index)
    price          = bids[min_deal_index][0]
    quantity       = bids[min_deal_index][1]

    return (price, quantity)
